/*************************************************************************
 Copyright (C) Unpublished Unis Software, Inc. All rights reserved.
 Unis Software, Inc., Confidential and Proprietary.

 This software is subject to copyright protection
 under the laws of the Public of China and other countries.

 Unless otherwise explicitly stated, this software is provided
 by Unis "AS IS".
 *************************************************************************/
package com.unis.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

/**
 * 时间格式转换工具类
 * 
 * @author CSJ (email:raulcsj@163.com)
 * @since 2013-1-25
 */
public class TimeUtil {
    private static final String DEFAULT_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat();

    private TimeUtil() {}

    /****************************************
     * 根据格式生成当前时间
     * 
     * @param pattern
     * @return
     ****************************************/
    public static final String getNow(String pattern) {
        if (StringUtils.isEmpty(pattern)) {
            pattern = DEFAULT_TIME_FORMAT;
        }
        dateFormat.applyPattern(pattern);
        return dateFormat.format(new Date());
    }

    public static final String getNow() {
        return getNow(null);
    }

    /****************************************
     * 解析时间字符串
     * 
     * @param data
     * @return
     ****************************************/
    public static final String parseDate(String data, String sourceFormat, String destFormat) {
        if (StringUtils.isEmpty(sourceFormat)) {
            sourceFormat = DEFAULT_TIME_FORMAT;
        }
        if (StringUtils.isEmpty(destFormat)) {
            destFormat = DEFAULT_TIME_FORMAT;
        }
        dateFormat.applyPattern(sourceFormat);
        try {
            Date time = dateFormat.parse(data);
            dateFormat.applyPattern(destFormat);
            return dateFormat.format(time);
        } catch (ParseException e) {
            return e.getMessage();
        }
    }

    public static final String parseDate(String data, String sourceFormat) {
        return parseDate(data, sourceFormat, null);
    }

    public static final String parseDate(String data) {
        return parseDate(data, null, null);
    }

}
